from django import forms
from .models import Host, NetworkDevice, IDC, Rack, Asset, AssetCategory, ResponsiblePerson

class HostForm(forms.ModelForm):
    SNMP_VERSION_CHOICES = [
        ('1', 'v1'),
        ('2c', 'v2c'),
        ('3', 'v3')
    ]

    # SNMP相关字段
    snmp_community = forms.CharField(
        label='SNMP团体名',
        required=False,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': '默认: public'
        })
    )
    snmp_port = forms.IntegerField(
        label='SNMP端口',
        required=False,
        initial=161,
        widget=forms.NumberInput(attrs={
            'class': 'form-control',
            'placeholder': '默认: 161'
        })
    )
    snmp_version = forms.ChoiceField(
        label='SNMP版本',
        choices=SNMP_VERSION_CHOICES,
        required=False,
        initial='2c',
        widget=forms.Select(attrs={
            'class': 'form-control'
        })
    )

    # SSH/IPMI认证字段
    username = forms.CharField(
        label='用户名',
        required=False,
        widget=forms.TextInput(attrs={'class': 'form-control'})
    )
    password = forms.CharField(
        label='密码',
        required=False,
        widget=forms.PasswordInput(attrs={'class': 'form-control'})
    )

    class Meta:
        model = Host
        fields = ['hostname', 'ip_address', 'monitor_type', 'status']
        widgets = {
            'hostname': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': '输入主机名'
            }),
            'ip_address': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': '输入IP地址'
            }),
            'monitor_type': forms.Select(attrs={
                'class': 'form-control'
            }),
            'status': forms.Select(attrs={
                'class': 'form-control'
            })
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 设置字段为非必填
        self.fields['status'].required = False
        
        # 如果是编辑现有主机，加载SNMP配置
        if self.instance.pk and self.instance.monitor_type == 'snmp':
            self.fields['snmp_community'].initial = self.instance.credentials.get('community', 'public')
            self.fields['snmp_port'].initial = self.instance.snmp_port
            self.fields['snmp_version'].initial = self.instance.snmp_version

    def clean(self):
        cleaned_data = super().clean()
        monitor_type = cleaned_data.get('monitor_type')
        
        # 如果是SNMP监控，验证SNMP相关字段
        if monitor_type == 'snmp':
            snmp_community = cleaned_data.get('snmp_community') or 'public'
            snmp_port = cleaned_data.get('snmp_port') or 161
            snmp_version = cleaned_data.get('snmp_version') or '2c'
            
            # 更新credentials字段
            cleaned_data['credentials'] = {
                'community': snmp_community,
                'version': snmp_version
            }
            # 更新SNMP相关字段
            cleaned_data['snmp_port'] = snmp_port
            cleaned_data['snmp_version'] = snmp_version
        
        return cleaned_data

    def save(self, commit=True):
        instance = super().save(commit=False)
        instance.credentials = self.cleaned_data['credentials']
        if commit:
            instance.save()
        return instance

class NetworkDeviceForm(forms.ModelForm):
    class Meta:
        model = NetworkDevice
        fields = ['name', 'ip_address', 'device_type', 'snmp_community', 'snmp_port', 'status']
        widgets = {
            'name': forms.TextInput(attrs={'class': 'form-control'}),
            'ip_address': forms.TextInput(attrs={'class': 'form-control'}),
            'device_type': forms.Select(attrs={'class': 'form-control'}),
            'snmp_community': forms.TextInput(attrs={'class': 'form-control'}),
            'snmp_port': forms.NumberInput(attrs={'class': 'form-control'}),
            'status': forms.Select(attrs={'class': 'form-control'}),
        }

class IDCForm(forms.ModelForm):
    class Meta:
        model = IDC
        fields = ['name', 'location', 'description']

class RackForm(forms.ModelForm):
    class Meta:
        model = Rack
        fields = ['name', 'position', 'capacity', 'power_capacity', 'x_position', 'y_position']

class AssetForm(forms.ModelForm):
    class Meta:
        model = Asset
        fields = ['name', 'asset_number', 'category', 'specification', 
                 'purchase_date', 'warranty_period', 'status',
                 'location', 'responsible_person', 'notes']
        widgets = {
            'purchase_date': forms.DateInput(attrs={'type': 'date'}),
            'notes': forms.Textarea(attrs={'rows': 3}),
        }

class AssetCategoryForm(forms.ModelForm):
    class Meta:
        model = AssetCategory
        fields = ['name', 'description']

class ResponsiblePersonForm(forms.ModelForm):
    class Meta:
        model = ResponsiblePerson
        fields = ['name', 'phone', 'email', 'department'] 